package com.mynetwork.activity;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.mynetwork.R;

import android.R.integer;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class WritewantedActivity extends FragmentActivity implements LocationListener {
	
	public String tag = "WritewantedActivity";
	
	private GoogleMap mmap;
	private LocationManager locationManager;
	private String provider;
	
	private TextView myAddress;
	
	private double latitude = 0;
	private double longitude = 0;
	
	private String addr = "";
	
	private EditText write_title;
	private EditText write_desc;
	private TextView write_time;
	private EditText reward;
	
	private String int_reward = "";
	
	private Button bt_send_data;
	
	private int year, month, day, hour, minute;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.writewanted);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		write_title = (EditText) findViewById(R.id.write_title);
		write_desc = (EditText) findViewById(R.id.write_desc);
		write_time = (TextView) findViewById(R.id.write_time);
		bt_send_data = (Button) findViewById(R.id.bt_send_data);
		reward = (EditText) findViewById(R.id.reward);
		
		
		GregorianCalendar calendar = new GregorianCalendar();
		year = calendar.get(Calendar.YEAR);
		 month = calendar.get(Calendar.MONTH);
         day= calendar.get(Calendar.DAY_OF_MONTH);
         hour = calendar.get(Calendar.HOUR_OF_DAY);
         minute = calendar.get(Calendar.MINUTE);
		

		GooglePlayServicesUtil.isGooglePlayServicesAvailable(WritewantedActivity.this);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, true);

		if (provider == null) { // 위치정보 설정이 안되어 있으면 설정하는 엑티비티로 이동합니다
			new AlertDialog.Builder(WritewantedActivity.this)
					.setTitle("위치서비스 동의")
					.setNeutralButton("이동",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									startActivityForResult(
											new Intent(
													android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
											0);
								}
							})
					.setOnCancelListener(
							new DialogInterface.OnCancelListener() {
								@Override
								public void onCancel(DialogInterface dialog) {
									finish();
								}
							}).show();
		} else { // 위치 정보 설정이 되어 있으면 현재위치를 받아옵니다
			locationManager.requestLocationUpdates(provider, 1, 1,
					WritewantedActivity.this);
			setUpMapIfNeeded();
		}
//		mmap.addMarker(new MarkerOptions().position(new LatLng(37.5213981, 127.0383319)).title("현재 내위치"));
		mark();
		setTime();
		sendData();
		
	}
	
	private void mark() {
		mmap.setOnMapClickListener(new OnMapClickListener() {
			@Override
			public void onMapClick(LatLng latLng) {
				latitude = latLng.latitude;
				longitude = latLng.longitude;
				setAddress();
				MarkerOptions markerOptions = new MarkerOptions();
				markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_icon));
				markerOptions.position(latLng);
				markerOptions.title(addr);
				mmap.clear();
				mmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
				mmap.addMarker(markerOptions);
				
				Log.e("주소", "" + addr);

			}
		});
		mmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {// 위치설정
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0:
			locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			Criteria criteria = new Criteria();
			provider = locationManager.getBestProvider(criteria, true);
			if (provider == null) {// 사용자가 위치설정동의 안했을때 종료
				finish();
			} else {// 사용자가 위치설정 동의 했을때
				locationManager.requestLocationUpdates(provider, 1L, 2F,
						WritewantedActivity.this);
				setUpMapIfNeeded();
			}
			break;
		}
	}

	@Override
	public void onBackPressed() {
		this.finish();
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUpMapIfNeeded();

	}

	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}

	private void setUpMapIfNeeded() {
		if (mmap == null) {
			mmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
			if (mmap != null) {
				setUpMap();
			}
		}
	}

	private void setUpMap() {
		mmap.setMyLocationEnabled(true);
		mmap.getMyLocation();

	}

	boolean locationTag = true;

	@Override
	public void onLocationChanged(Location location) {
		if (locationTag) {// 한번만 위치를 가져오기 위해서 tag를 주었습니다
			Log.e("myLog", "onLocationChanged: !!" + "onLocationChanged!!");
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			mmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15));
			locationTag = false;
		}

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
	
	public String getAddress(double lat, double lng){
		String address = null;
		
		Geocoder geocoder = new Geocoder(this, Locale.getDefault());
		
		List<Address> list = null;
		
		try {
			list = geocoder.getFromLocation(lat, lng, 1);
		} catch (Exception e) {
			Log.e(tag, "" + e);
		}
		
		if (list == null) {
			Log.e(tag, "주소 데이터 얻기 실패");
			return null;
		}
		if (list.size() > 0 ) {
			Address addr = list.get(0);
			
			if (addr.getSubLocality() != null) {
				address = addr.getLocality() + " "
						+ addr.getSubLocality() + " "
						+ addr.getThoroughfare() + " "
						+ addr.getFeatureName();
			}else {
				address = addr.getLocality() + " "
						+ addr.getThoroughfare() + " "
						+ addr.getFeatureName();
			}
			
		}
		
		
		return address;
	}
	
	public void setAddress(){
		myAddress = (TextView) findViewById(R.id.myAddress);
		addr =  getAddress(latitude, longitude);
		myAddress.setText(addr);
	}
	
	public void setTime(){
		write_time.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new DatePickerDialog(WritewantedActivity.this, dateSetListner, year, month, day).show();
			}
		});
	}
	
	private DatePickerDialog.OnDateSetListener dateSetListner = new DatePickerDialog.OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			String msg = String.format("%d-%d-%d", year, monthOfYear + 1, dayOfMonth);
			Toast.makeText(WritewantedActivity.this, msg, 1000).show();
			write_time.setText(msg);
			
		}
	};
	
	private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
		
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			String msg = String.format("%d / %d / %d", year, hourOfDay, minute);
            Toast.makeText(WritewantedActivity.this, msg, Toast.LENGTH_SHORT).show();
		}
	};
	
	private void sendData(){
		
		bt_send_data.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				makejson();
			}
		});
	}
	
	
	public void makejson(){
		JSONObject obj = new JSONObject();
		try {
			obj.put("cmd", "contInsert");
			obj.put("userIdx", 1);
			obj.put("title", write_title.getText());
			obj.put("contDesc", write_desc.getText());
			obj.put("happenDate", write_time.getText());
			obj.put("happenTime", "1");
			obj.put("address", myAddress.getText());
			obj.put("latitude", latitude);
			obj.put("longitude", longitude);
			obj.put("categoryIdx", 1);
			obj.put("reward", Integer.parseInt(reward.getText().toString()));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Log.e(tag, "" + obj);
	}

}
